/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            佛祖保佑       永无BUG
*/

$NG.AllReady(function (
	page,
	{ useAction, useValuesChange, useUpdateRows, useDataIndexChange, useClick, useBeforeClick }
) {
	const mstform = $NG.getCmpApi("p_form_employ_task");
	const dgrid1 = $NG.getCmpApi("p_form_employ_task_d");
    if(page.oType == 'add'){
        setTimeout(()=>{
            console.log(`获取当前用户信息`,$NG.getUser().logid, $NG.getUser())
            getInfo("GetSsInfo", $NG.getUser().logid)
            $NG.message("正在获取当前登录用户信息~")
        },200)
    }
	useValuesChange(({ args }) => {
        getInfo()
		getTaskInfo();
        // getUserInfo()
	}, "p_form_employ_task.u_name");

    useValuesChange(({args})=>{
        // cntMFilter()
        getName()
    },"p_form_employ_task.phid_pc")

    //判断是不是列表页面
    if(page.isList){
        console.log(`当前是列表页面`);
        //获取工具栏
        const toolbar = $NG.getCmpApi("toolbar")
        toolbar.insert({
            id: "toNewPage",
            text: "填写实际用工任务书",
            iconCls: "icon-New"
        });
        useClick((args)=>{
            console.log(`点击成功`,);
            const checkData = page.getSelectedRecord()
            const app_status = checkData[0].app_status
            if(app_status !==1){
                $NG.alert("单据未审核！")
                return false
            }
            if (checkData.length>1){
                $NG.alert("请单选~~~")
                return false
            }
            const model = checkData[0]
            if(checkData&&checkData.length != 0){
                const phid = model.phid
                $NG.open(`http://nginx.clouddev.hisense.com/react/index.html#/customform/detail?otype=add&busType=EFORM9000000192&isSso=1&AppTitle=%E7%94%A8%E5%B7%A5%E5%AE%9E%E9%99%85%E4%BB%BB%E5%8A%A1%E4%B9%A6%E5%A1%AB%E6%8A%A5-%E6%96%B0%E5%A2%9E&treeOcode=1&sourceid=${phid}&intype=click&treePc=&treePcName=`)
            }else{
                $NG.alert("请选中行~")
            }
        },"toNewPage")
    }

	useUpdateRows(({ args }) => {
		console.log(`表格监听`);
		const _d1arr = dgrid1.getRows();
		let u_self_score = 0;
		let u_reevaluate_score = 0;
		_d1arr.forEach((element) => {
			u_self_score += element.u_self_score ? element.u_self_score : 0;
			u_reevaluate_score += element.u_reevaluate_score
				? element.u_reevaluate_score
				: 0;
		});
		console.log("数组", u_reevaluate_score, u_self_score);
		$NG.updateState((updater) => {
			updater.data.p_form_employ_task.setProps({
				u_self_score: u_self_score,
				u_reevaluate_score: u_reevaluate_score,
			});
		});
	}, "p_form_employ_task_d");
	if(page.oType == 'add'){
        getTaskInfo();
    }
    useDataIndexChange(({args})=>{
        const rows = dgrid1.getRows()
        const total = rows.reduce((value,item)=>{
            value+=(Number(item.u_score) || 0)
            return value
        },0)
        if(total>100){
            args[0].u_score = 0
            $NG.alert("分值总和不能超过100分")
        }
    },"u_score")
    useBeforeClick(async function ({ args }) {
        //按钮点击前事件
        const rows = dgrid1.getRows()
        const total = rows.reduce((value,item)=>{
            value+=(Number(item.u_score) || 0)
            return value
        },0)
        if(total < 100){
            $NG.alert("分值总和小于100,请重新校验")
            return false; // 取消向下执行
        }
        return true; 
    }, "save");
    getName()
    function getName() {
        $NG.updateUI((updater) => {
            const fields = ["u_name"];
            fields.forEach((field) => {
                // $NG.getPageUI();
                // 根据组件目录设置路径，可能存在
                // fieldSetForm
                // PCFieldSetPanelGroup[i][field]
                updater.fieldSetForm.p_form_employ_task[field].setProps({
                    // hidden: true, //隐藏
                    // required: true, //必输
                    // disabled: true, //只读
                    onBeforeOpen: async () => {
                        var phid_pc = mstform.getItem('phid_pc').getValue();
                        if (!phid_pc) {
                            $NG.alert("请先选择项目");
                            return false;
                        } else {
                            return true;
                        }
                    },
                    clientSqlFilter: `xm = '${mstform.getItem('phid_pc').getValue()}'  and ry_zt = '32'`, //过滤条件
                    // placeholder: "请选择", //输入框字段加提示语
                    // data: [{ value: "01", label: "实施外包用工" }], //下拉过滤
                });
            });
        });
    }
    function getInfo(name="getWbInfo",phid = mstform.getItem("u_name").getValue()){
        $NG.execServer(name, {yg:phid}, function (res){
            console.log('获取人员信息',res);
            if(res.msg == "Has no data!" || res.count == 0) {
                $NG.alert("无法获取到当前用户登录的信息！")
                return
             }
            console.log(`人员信息获取`,JSON.parse(res.data));
            const _data = JSON.parse(res.data)[0].extendObjects
             mstform.getItem('u_name').setValue({
                label:_data.ry_name,
                value:_data.yfphid
             })
             mstform.getItem('phid_pc').setValue({
                value:_data.xm,
                label:_data.xm_name
             })
             mstform.getItem('u_employment_type').setValue(_data.yglx)
        } )
    }
    function getTaskInfo() {
		dgrid1.clearRows();
		$NG.execServer("getTaskInfo", {}, (res) => {
			const _data = JSON.parse(res.data);
			console.log(`获取用工模板`, _data, res);
			const _rowArr = [];
			_data.forEach((element) => {
				_rowArr.push({
					u_type: element.extendObjects.u_category,
					u_score: element.extendObjects.u_score,
				});
			});
			dgrid1.addRows(_rowArr);
		});
	}

    // cntMFilter()
    function cntMFilter() {
		if (!mstform.getItem("phid_pc").getValue()) {
			return;
		}
		$NG.updateUI((updater, state) => {
			updater.fieldSetForm.p_form_employ_task.u_name.setProps({
				onBeforeOpen: async () => {
					var phid_pc = $NG
						.getCmpApi("p_form_employ_task")
						.getItem("phid_pc")
						.getValue();
					if (!phid_pc) {
						$NG.alert("请先选择项目");
						return false;
					} else {
						return true;
					}
				},
				...(!!$NG
					.getCmpApi("p_form_employ_task")
					.getItem("phid_pc")
					.getValue() && {
					clientSqlFilter: {
						xm: $NG
							.getCmpApi("p_form_employ_task")
							.getItem("phid_pc")
							.getValue(),
					},
				}),
			});
		});
	}

	function getUserInfo() {
		$NG.execServer(
			"getWbInfo",
			{ yg: mstform.getItem("u_name").getValue() },
			function (res) {
				console.log(`人员信息获取`, JSON.parse(res.data), res);
				const _data = JSON.parse(res.data)[0].extendObjects;
				$NG.updateState((updater) => {
					updater.data.p_form_employ_task.setProps({
						u_sex: _data.xb == "1" ? "男" : "女",
						phid_pc: {
							label: _data.xm_name,
							value: _data.xm,
						},
						idno: _data.sfz,
						u_employment_position: {
							label: _data.gwmc,
							value: _data.gw,
						},
						u_division: {
							label: _data.syb_name,
							value: _data.syb,
						},
						u_employment_type: _data.yglx,
						u_entry_dt: _data.rzsj,
						u_cnt_end_dt: _data.dqsj,
					});
				});
			}
		);
	}
});
